/*
 * @Author: your name
 * @Date: 2021-09-12 11:49:15
 * @LastEditTime: 2022-01-16 15:45:55
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \phone\src\time_out.cpp
 */
#include "time_out.h"
#include "xlog.h"
#include <thread>
TimeOut::TimeOut(unsigned int timeOut)
{
    runningTime = 0;
    TimeOut::timeOut = timeOut;
    run = false;
    loop = false;
    StartCountDown();
}
TimeOut::~TimeOut()
{
    StopCountDown();
    /**
     * @brief
     * 休眠一段时间，保证线程正常退出，解决未知原因的崩溃问题。
     * TODO: 是否可以优化？因为睡眠会造成短暂的阻塞带来界面体验性问题。
     */
    std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME + 50));
}
void TimeOut::CountDown()
{
    while (run)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME));
        runningTime += SLEEP_TIME;
        if (runningTime >= timeOut)
        {
            TimeOutEvent();
            if (loop)
            {
                /**
                 * @brief 
                 * 超时循环，当计时器使用。
                 */
                runningTime = 0;
                continue;
            }
            break;
        }
    }
}
void TimeOut::ResetTimeOut()
{
    runningTime = 0;
}
void TimeOut::StartCountDown()
{
    if (run || 0 == timeOut)
    {
        return;
    }
    run = true;
    std::thread t(&TimeOut::CountDown, this);
    t.detach(); //设置线程分离属性，线程结束后自动释放资源
}
void TimeOut::StopCountDown()
{
    run = false;
}
void TimeOut::ResetRunningTime()
{
    runningTime = 0;
}
void TimeOut::SetTimeOut(unsigned int timeOut)
{
    TimeOut::timeOut = timeOut;
    if (0 == timeOut)
    {
        run = false;
    }
    runningTime = 0;
    StartCountDown();
}
void TimeOut::SetLoop(bool value)
{
    loop = value;
}
